package com.terrynoya.fight.commands
{
	import com.terrynoya.fight.emuns.ButtonState;

	public class CommandChecker
	{
		public static const INT_MIN:int = int.MIN_VALUE;
		
		public static function check(command:InputCommand,input:InputBuffer):Boolean
		{
			var elementIndex:int = command.elements.length - 1;
			
			for (var inputIndex:int = 0; inputIndex < input.size; inputIndex++) 
			{
				var matchIndex:int = scanForMatch(command,elementIndex,input,inputIndex);
				if(matchIndex == INT_MIN)
				{
					return false;
				}
				
				if(elementIndex > 0)
				{
					elementIndex--;
					inputIndex = matchIndex;
				}
				else if(elementIndex == 0)
				{
					return matchIndex <= command.time;
				}
				else
				{
					return false;
				}
			}
			return false;
		}
		
		public static function scanForMatch(command:InputCommand,elementIndex:int,input:InputBuffer,inputIndex:int):int
		{
			var element:CommandElement = command.elements[elementIndex];
			var scanLen:int = Math.min(input.size,command.time);
			
			for (var i:int = inputIndex; i < scanLen; i++) 
			{
				if(elementIndex == command.elements.length - 1)
				{
					if(element.triggerOnRelease == false)
					{
						if(i != inputIndex)
						{
							return INT_MIN;
						}
					}
					else
					{
						if(i - 1 != inputIndex && i != inputIndex)
						{
							return INT_MIN;
						}
					}
				}
				
				if(elementMatch(element,input,inputIndex))
				{
					return i;
				}
			}
			return INT_MIN;
		}
		
		public static function elementMatch(element:CommandElement,input:InputBuffer,inputIndex:int):Boolean
		{
			var state:int = input.getState(inputIndex,element);
			if(element.heldDown)
			{
				var rlt:Boolean = (state == ButtonState.Down || state == ButtonState.Pressed);
				return rlt;
			}
			else if(element.triggerOnRelease == true)
			{
				if(inputIndex >= input.size)
				{
					return false;
				}
				
				if(inputIndex == 0 || input.getState(inputIndex - 1,element) != ButtonState.Released)
				{
					return false;
				}
				
				var holdCount:int = 1;
				for (var i:int = inputIndex; i < input.size; holdCount++) 
				{
					if(input.getState(i,element) != ButtonState.Down)
					{
						break;
					}
				}
				
				if(holdCount < element.triggerTime)
				{
					return false;
				}
				
			}
			else
			{
				if(state != ButtonState.Pressed)
				{
					return false;
				}
			}
			return true;
		}
	}
}